<?php
namespace app\admin\controller;
use app\admin\controller\AdminBaseController;
use think\Cache;
use think\Db;

/**
 * 系统配置
 * Class System
 */
class SystemController extends BaseController {
	protected function _initialize() {
		parent::_initialize();
		if(session('ADMIN.id') !=1){
			$this->error('没有权限');
		}
		
	}
    /**
     * 站点配置
     */
    public function index() {
		if ($this->request->isPost()) {
            $site_config   = $this->request->post('site_config/a');
            $data['value'] = serialize($site_config);
            if (Db::name('system')->where('name', 'site_config')->update($data) !== false) {
                Cache::set('site_config', $site_config);
                $this->success('提交成功');
            } else {
                $this->error('提交失败');
            }
        }else{
        	if (Cache::has('site_config')) {
	            $site_config = Cache::get('site_config');
	        } else {
	            $site_config = Db::name('system')->field('value')->where('name', 'site_config')->find();
	            $site_config = unserialize($site_config['value']);
	        }
        	return $this->fetch('index', ['site_config' => $site_config]);
        }
    }
    /**
	 * 后台菜单
	 * @return mixed
	 */
	public function menu() {
		$admin_menu_list = db('auth_rule')->order('sort ASC,id ASC')->select();
		$admin_menu_level_list = array2level($admin_menu_list);
		$this->assign('admin_menu_level_list', $admin_menu_level_list);
		return $this->fetch();
	}

	/**
	 * 保存菜单
	 */
	public function menu_add($pid = '') {
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$validate = $this->validate($data, 'AuthRule');
			if ($validate !== true) {
				$this->error($validate);
			}
			if (db('auth_rule')->insert($data)) {
				$this->success('保存成功');
			} else {
				$this->error('保存失败');
			}
		} else {
			return $this->fetch('add', array('pid' => $pid));
		}
	}

	/**
	 * 更新菜单
	 * @param $id
	 */
	public function menu_update($id) {
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$validate = $this->validate($data, 'AuthRule');
			if ($validate !== true) {
				$this->error($validate);
			}
			if (db('auth_rule')->update($data, $id) !== false) {
				$this->success('更新成功');
			} else {
				$this->error('更新失败');
			}
		} else {
			$admin_menu = db('auth_rule')->find($id);
			return $this->fetch('update', array('admin_menu' => $admin_menu));
		}
	}
	
	
}
